﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Drawing;
using System.Reflection;
using DevExpress.XtraGrid;
using DevExpress.XtraEditors;
using DevExpress.XtraExport;
using DevExpress.XtraPrinting;
using THSLib;
using THSERP.BusinessEntities;
namespace THSERP.BaseProvider
{
    public partial class THSGridControl : DevExpress.XtraGrid.GridControl, ICloneable
    {
        #region Variables
        protected THSERPScreen _screen;
        protected String _THSDataSource;
        protected String _THSFieldGroup;
        protected String _THSComment;
        protected String _THSError;
        protected DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hitInfo = null;
        protected String _THSPrivilege;
        protected  String _THSSelectType;
        protected  String _THSSelectTypeValue;
        #endregion

        #region Public Properties
        public THSERPScreen Screen
        {
            get
            {
                return _screen;
            }
            set
            {
                _screen = value;
            }
        }

        [Category("THS")]
        public String THSFieldGroup
        {
            get
            {
                return _THSFieldGroup;
            }
            set
            {
                _THSFieldGroup = value;
            }
        }

        [Category("THS")]
        public String THSDataSource
        {
            get
            {
                return _THSDataSource;
            }
            set
            {
                _THSDataSource = value;
            }
        }

        [Category("THS")]
        public String THSComment
        {
            get
            {
                return _THSComment;
            }
            set
            {
                _THSComment = value;
            }
        }

        [Category("THS")]
        public String THSError
        {
            get
            {
                return _THSError;
            }
            set
            {
                _THSError = value;
            }
        }

        [Category("THS")]
        public String THSPrivilege
        {
            get
            {
                return _THSPrivilege;
            }
            set
            {
                _THSPrivilege = value;
            }
        }
        [Category("THS")]
        public  String THSSelectType
        {
            get
            {
                return _THSSelectType;
            }
            set
            {
                _THSSelectType = value;
            }
        }

        [Category("THS")]
        public  String THSSelectTypeValue
        {
            get
            {
                return _THSSelectTypeValue;
            }
            set
            {
                _THSSelectTypeValue = value;
            }
        }
        #endregion

        #region Constructor
        public THSGridControl()
        {
            InitializeComponent();

            this.MainView = (DevExpress.XtraGrid.Views.Grid.GridView)this.MainView;
        }

        public THSGridControl(IContainer container)
        {
            container.Add(this);

            InitializeComponent();

            this.MainView = (DevExpress.XtraGrid.Views.Grid.GridView)this.MainView;
        }
        #endregion

        #region Function for init GridControl
        public virtual void InitializeControl()
        {
            //Init Common Properties for GridControl Control
            InitializeCommonProperties();

            //3.Init GridControl View and columns     
            DevExpress.XtraGrid.Views.Grid.GridView gridView = InitializeGridView();
            //this.ViewCollection.Add(gridView);
            this.MainView = gridView;

            //Init DataSource
            InitGridControlDataSource();

           
           this.UseEmbeddedNavigator = true;
            this.EmbeddedNavigator.Name = "navigator_" + this.Name;
            this.EmbeddedNavigator.Buttons.CustomButtons.AddRange(new DevExpress.XtraEditors.NavigatorCustomButton[] { new DevExpress.XtraEditors.NavigatorCustomButton(8, "Customize"), new DevExpress.XtraEditors.NavigatorCustomButton(9, "Save Customization"), new DevExpress.XtraEditors.NavigatorCustomButton(0,6, "Refresh"), new DevExpress.XtraEditors.NavigatorCustomButton(11, "Export"), new DevExpress.XtraEditors.NavigatorCustomButton(12, "Print")});
            //this.EmbeddedNavigator.Buttons.CustomButtons.AddRange(new DevExpress.XtraEditors.NavigatorCustomButton[] { new DevExpress.XtraEditors.NavigatorCustomButton(8,8, "Customize"), new DevExpress.XtraEditors.NavigatorCustomButton(9,9, "Save Customization"), new DevExpress.XtraEditors.NavigatorCustomButton(5,12, "Print"), new DevExpress.XtraEditors.NavigatorCustomButton(4,11, "Export"), new DevExpress.XtraEditors.NavigatorCustomButton(3,3, "Refresh") });
            this.EmbeddedNavigator.Buttons.Edit.Visible = false;
            this.EmbeddedNavigator.Buttons.Remove.Visible = false;
            this.EmbeddedNavigator.Buttons.Append.Visible = false;
            this.EmbeddedNavigator.ButtonClick += new DevExpress.XtraEditors.NavigatorButtonClickEventHandler(NavigatorButton_Click);
            this.DataSourceChanged += new EventHandler(THSGridControl_DataSourceChanged);
            gridView.ValidateRow += new DevExpress.XtraGrid.Views.Base.ValidateRowEventHandler(GridView_ValidateRow);
        }

        

        protected void InitializeCommonProperties()
        {

        }

        public virtual void InitGridControlDataSource()
        {
            
        }

        #region Function for init GridControl View
        protected virtual DevExpress.XtraGrid.Views.Grid.GridView InitializeGridView()
        {
            DevExpress.XtraGrid.Views.Grid.GridView gridView = (DevExpress.XtraGrid.Views.Grid.GridView)this.ViewCollection[0];
            gridView.Name = "fld_dgv" + this.Name.Substring(7);
            gridView.OptionsBehavior.Editable = true;
            gridView.OptionsView.ShowGroupPanel = false;
            
            gridView.OptionsView.ColumnAutoWidth = false;
            gridView.OptionsView.ShowDetailButtons = false;            

            gridView.OptionsNavigation.EnterMoveNextColumn = true;

            gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
            gridView.OptionsCustomization.AllowFilter = true;

            gridView.GridControl = this;

            InitGridViewColumns(gridView);

           
            ERPModuleEntities entity = ((BaseModuleERP)Screen.Module).CurrentModuleEntity;
            try
            {
                gridView.InitNewRow += new DevExpress.XtraGrid.Views.Grid.InitNewRowEventHandler(GridView_InitNewRow);
                gridView.FocusedRowChanged += new DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventHandler(GridView_FocusedRowChanged);
                gridView.Click += new EventHandler(GridView_Click);
                gridView.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(GridView_CellValueChanged);
                gridView.KeyUp += new KeyEventHandler(GridView_KeyUp);
               gridView.RowStyle+=new DevExpress.XtraGrid.Views.Grid.RowStyleEventHandler(GridView_RowStyle);
                //gridView.ValidateRow += new DevExpress.XtraGrid.Views.Base.ValidateRowEventHandler(GridView_ValidateRow);
                gridView.InvalidRowException += new DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventHandler(GridView_InvalidRowException);
                gridView.ValidatingEditor += new DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventHandler(GridView_ValidatingEditor);
            }
            catch (Exception)
            {
            }
            return gridView;
        }



        protected virtual void InitGridViewColumns(DevExpress.XtraGrid.Views.Grid.GridView gridView)
        {
            gridView.Columns.Clear();
            InitDefaultGridViewColumns(gridView);

           
            AddColumnsToGridView(THSDataSource, gridView);

            //Init GridControl Column visible index
            InitGridColumnsVisibleIndex(gridView);

        }

        protected virtual void InitDefaultGridViewColumns(DevExpress.XtraGrid.Views.Grid.GridView gridView)
        {

        }

        protected virtual void InitGridColumnsVisibleIndex(DevExpress.XtraGrid.Views.Grid.GridView gridView)
        {
            STFieldsInfo objSTFieldsInfo = new STFieldsController().GetFieldBySTModuleIDAndSTUserGroupIDAndSTFieldName(
                                                            ((BaseModuleERP)Screen.Module).ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                            this.Name);
            if (objSTFieldsInfo != null)
            {
                STFieldColumnsController objSTFieldColumnsController = new STFieldColumnsController();
                DataSet dsColumns = objSTFieldColumnsController.GetFieldColumnsByFieldID(objSTFieldsInfo.STFieldID);
                if (dsColumns.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow rowColumn in dsColumns.Tables[0].Rows)
                    {
                        STFieldColumnsInfo objSTFieldColumnsInfo = (STFieldColumnsInfo)objSTFieldColumnsController.GetObjectFromDataRow(rowColumn);
                        if (gridView.Columns[objSTFieldColumnsInfo.STFieldColumnFieldName] != null)
                        {
                            gridView.Columns[objSTFieldColumnsInfo.STFieldColumnFieldName].VisibleIndex = objSTFieldColumnsInfo.STFieldColumnVisibleIndex;
                            gridView.Columns[objSTFieldColumnsInfo.STFieldColumnFieldName].Width = objSTFieldColumnsInfo.STFieldColumnWidth;
                        }
                    }
                }
                else
                    InitDefaultGridColumnsVisibleIndex(gridView);
            }
            //Init Default Column visible index
            else
            {
                InitDefaultGridColumnsVisibleIndex(gridView);
            }
        }

        protected virtual void InitDefaultGridColumnsVisibleIndex(DevExpress.XtraGrid.Views.Grid.GridView gridView)
        {

        }

        #endregion
        #endregion

        #region Function for GridControl Event Handlers

        protected virtual void GridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            
        }

        protected virtual void GridView_Click(object sender, EventArgs e)
        {
            
        }

        protected virtual void GridView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            
        }

        protected virtual void GridView_KeyUp(object sender, KeyEventArgs e)
        {

        }

        protected virtual void GridView_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            
        }

        protected virtual void GridView_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
 
        }

        protected virtual void GridView_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {

        }

        protected virtual void GridView_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            
        }
        protected virtual void THSGridControl_DataSourceChanged(object sender, EventArgs e)
        {

        }
        protected virtual void GridView_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            
        }
        protected void GridControl_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }

        protected void GridControl_MouseDown(object sender, MouseEventArgs e)
        {
            DevExpress.XtraGrid.GridControl gridControl = (DevExpress.XtraGrid.GridControl)sender;
            hitInfo = ((DevExpress.XtraGrid.Views.Grid.GridView)gridControl.ViewCollection[0]).CalcHitInfo(new Point(e.X, e.Y));
            if (hitInfo.RowHandle < 0) hitInfo = null;
        }

        protected virtual object GetDataObject(object sender, IDataObject data, String strFieldName)
        {
            object[] objDrag = data.GetData(typeof(object[])) as object[];
            if (objDrag[0] is Int32 && objDrag[1] is DevExpress.XtraGrid.Views.Grid.GridView)
            {
                DevExpress.XtraGrid.Views.Grid.GridView gridView = objDrag[1] as DevExpress.XtraGrid.Views.Grid.GridView;
                return gridView.GetRowCellValue(Convert.ToInt32(objDrag[0]), strFieldName);
            }
            else
                return null;
        }

        protected virtual void GridControl_MouseMove(object sender, MouseEventArgs e)
        {
            DevExpress.XtraGrid.GridControl gridControl = (DevExpress.XtraGrid.GridControl)sender;

            if (hitInfo == null)
                return;
            if (e.Button != MouseButtons.Left)
                return;
            Rectangle dragRect = new Rectangle(new Point(
            hitInfo.HitPoint.X - SystemInformation.DragSize.Width / 2,
            hitInfo.HitPoint.Y - SystemInformation.DragSize.Height / 2), SystemInformation.DragSize);

            if (!dragRect.Contains(new Point(e.X, e.Y)))
            {
                if (hitInfo.InRowCell)
                {
                    gridControl.DoDragDrop(new object[] { hitInfo.RowHandle, gridControl.ViewCollection[0] }, DragDropEffects.All);
                }
            }
        }
        #endregion

        #region New Functions
        public static THSGridControl Instance(String strInstanceName, String strModuleName)
        {
            if (!String.IsNullOrEmpty(strInstanceName))
            {
                Type gridType = THSApp.THSERPAssembly.GetType("THSERP.Modules." + strModuleName + "." + strInstanceName + "GridControl");
                if (gridType != null)
                {
                    return (THSGridControl)gridType.InvokeMember("", BindingFlags.CreateInstance, null, null, null);
                }
                else
                {
                    gridType = THSApp.THSERPAssembly.GetType("THSERP." + strInstanceName + "GridControl");
                    if (gridType != null)
                        return (THSGridControl)gridType.InvokeMember("", BindingFlags.CreateInstance, null, null, null);
                    else
                        return new THSGridControl();
                }
            }
            else
                return new THSGridControl();
        }

        protected virtual DevExpress.XtraGrid.Columns.GridColumn InitGridColumn(String strTableName, int iVisibleIndex, String strFieldName, String strCaption, int iWidth)
        {
            DevExpress.XtraGrid.Columns.GridColumn column = new DevExpress.XtraGrid.Columns.GridColumn();
            column.Name = "col" + strFieldName;
            column.Caption = strCaption;
            column.FieldName = strFieldName;
            column.VisibleIndex = iVisibleIndex;
            column.Width = iWidth;
            return column;
        }

        protected virtual DevExpress.XtraGrid.Columns.GridColumn InitUnboundGridColumn(int iVisibleIndex, String strColumnName, String strColumnType, String strCaption, int iWidth)
        {
            DevExpress.XtraGrid.Columns.GridColumn column = new DevExpress.XtraGrid.Columns.GridColumn();
            column.Name = strColumnName;
            column.Caption = strCaption;
            column.FieldName = strColumnName;
            column.UnboundType = (DevExpress.Data.UnboundColumnType)Enum.Parse(typeof(DevExpress.Data.UnboundColumnType), strColumnType);
            column.VisibleIndex = iVisibleIndex;
            column.Width = iWidth;

            return column;
        }

        protected virtual DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit InitColumnLookupEdit(String strTableName, String strColumnName)
        {
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit rep = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            rep.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
            rep.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoFilter;
            rep.NullText = String.Empty;

            
            String strLookupTable = THSDbUtil.GetPrimaryTableWhichForeignColumnReferenceTo(strTableName, strColumnName);
            THSApp.InitDataToLookupTable(strLookupTable);
            if (THSApp.LookupTables[strLookupTable] == null)
                return null;
            String strPrimaryColumn = THSDbUtil.GetTablePrimaryColumn(strLookupTable);
            String strDisplayColumn = GetLookupTableDisplayColumn(strLookupTable);
            rep.ValueMember = strPrimaryColumn;
            rep.DisplayMember = strDisplayColumn;
            DataSet ds = (DataSet)THSApp.LookupTables[strLookupTable];
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    if (Convert.ToInt32(ds.Tables[0].Rows[0][rep.ValueMember]) > 0)
                    {
                        DataRow row = ds.Tables[0].NewRow();

                        row[rep.DisplayMember] = String.Empty;
                        row[rep.ValueMember] = 0;
                        ds.Tables[0].Rows.InsertAt(row, 0);
                    }
                }
            }

            rep.DataSource = ds.Tables[0];
            
            rep.QueryPopUp += new CancelEventHandler(RepositoryItemLookupEdit_QueryPopup);
            DevExpress.XtraEditors.Controls.LookUpColumnInfo colName = new DevExpress.XtraEditors.Controls.LookUpColumnInfo();
            colName.FieldName = strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "No";
            colName.Caption = "No";
            colName.Width = 100;

            rep.Columns.Add(colName);

            return rep;
        }

        protected virtual String GetLookupTableDisplayColumn(String strLookupTableName)
        {
           
            String strPrimaryColumn = THSDbUtil.GetTablePrimaryColumn(strLookupTableName);
            String prefix = strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2);
            if (THSDbUtil.ColumnIsExist(strLookupTableName, prefix + "Name"))
                return prefix + "Name";
            else if (THSDbUtil.ColumnIsExist(strLookupTableName, prefix + "No"))
                return prefix + "No";
            return String.Empty;
        }

        protected virtual void RepositoryItemLookupEdit_QueryPopup(object sender, CancelEventArgs e)
        {
           
            DevExpress.XtraEditors.LookUpEdit lke = (DevExpress.XtraEditors.LookUpEdit)sender;
            String strLookupTable = lke.Properties.ValueMember.Substring(0, lke.Properties.ValueMember.Length - 2) + "s";
          THSApp.InitDataToLookupTable( strLookupTable );
            if ( THSApp.LookupTables[strLookupTable]==null )
                    return;
		    DateTime dtLastCreatedDate = THSDbUtil.GetLastCreatedDateOfTable(strLookupTable);
            DateTime dtLastUpdatedDate = THSDbUtil.GetLastUpdatedDateOfTable(strLookupTable);
            DateTime dtLastLookupUpdate= (DateTime)THSApp.LookupTablesUpdatedDate[strLookupTable] ;
            if ( dtLastUpdatedDate>= dtLastLookupUpdate )
            {
                //Refesh Data Source
                BaseBusinessController objLookupTableController = BusinessControllerFactory.GetBusinessController(strLookupTable + "Controller");
                if (objLookupTableController != null)
                {
                    DataSet ds = objLookupTableController.GetAllObjects();

                    if (ds.Tables.Count > 0)
                    {
                        //hieu.nguyen remove 10/08/2011
                        //BindingSource bds = new BindingSource();
                        //bds.DataSource = ds.Tables[0];
                        //lke.Properties.DataSource = bds;
                        //bds.ResetBindings(false);

                        // Update Last Updated Date of Lookup Table
                        THSApp.LookupTablesUpdatedDate[strLookupTable] = DateTime.Now;
                        ((DataSet)THSApp.LookupTables[strLookupTable]).Tables.Clear();
                        ((DataSet)THSApp.LookupTables[strLookupTable]).Tables.Add(ds.Tables[0].Copy());
                        lke.Properties.DataSource=( (DataSet)THSApp.LookupTables[strLookupTable] ).Tables[0];      
                    }
                }
            }
        }

        protected virtual DevExpress.XtraEditors.Repository.RepositoryItemTextEdit InitColumnAmountTextEdit(int iDecimal)
        {
            DevExpress.XtraEditors.Repository.RepositoryItemTextEdit repItemTextEdit = new DevExpress.XtraEditors.Repository.RepositoryItemTextEdit();
            repItemTextEdit.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
            repItemTextEdit.Mask.EditMask = String.Format("f{0}", iDecimal.ToString());
            repItemTextEdit.Mask.UseMaskAsDisplayFormat = true;

            return repItemTextEdit;
        }

        protected virtual void AddColumnsToGridView(String strTableName, DevExpress.XtraGrid.Views.Grid.GridView gridView)
        {
            //Add bound columns
           
            AAColumnAliasController objAAColumnAliasController = new AAColumnAliasController();
            DataSet dsColumns = objAAColumnAliasController.GetAAColumnAliasByTableName(strTableName);
            if (dsColumns.Tables.Count > 0)
            {
                foreach (DataRow rowColumn in dsColumns.Tables[0].Rows)
                {
                    AAColumnAliasInfo objAAColumnAliasInfo = (AAColumnAliasInfo)objAAColumnAliasController.GetObjectFromDataRow(rowColumn);
                    if (objAAColumnAliasInfo != null)
                    {
                        if (gridView.Columns.ColumnByFieldName(objAAColumnAliasInfo.AAColumnAliasName) == null)
                        {
                            DevExpress.XtraGrid.Columns.GridColumn column = InitGridColumn(strTableName, -1, objAAColumnAliasInfo.AAColumnAliasName, objAAColumnAliasInfo.AAColumnAliasCaption, 50);
                            
                            if (THSDbUtil.IsForeignKey(strTableName, objAAColumnAliasInfo.AAColumnAliasName))
                            {
                                DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupEdit = InitColumnLookupEdit(strTableName, objAAColumnAliasInfo.AAColumnAliasName);
                                if (repLookupEdit != null)
                                    column.ColumnEdit = repLookupEdit;
                            }
                            else
                            {
                                String strConfigValueTable = String.Empty;

                                if (objAAColumnAliasInfo.AAColumnAliasName.EndsWith("Combo"))
                                    strConfigValueTable = objAAColumnAliasInfo.AAColumnAliasName.Substring(2, objAAColumnAliasInfo.AAColumnAliasName.Length - 7);
                                else
                                    strConfigValueTable = objAAColumnAliasInfo.AAColumnAliasName.Substring(2, objAAColumnAliasInfo.AAColumnAliasName.Length - 2);

                              
                                if (ADConfigValueUtility.glbdsConfigValues.Tables[strConfigValueTable] != null)
                                {
                                    DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupEdit = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
                                    repLookupEdit.ValueMember = "Value";
                                    repLookupEdit.DisplayMember = "Text";
                                    DataTable dtSource = ADConfigValueUtility.glbdsConfigValues.Tables[strConfigValueTable];
                                    if (dtSource.Rows.Count > 0)
                                    {
                                        if (!String.IsNullOrEmpty(dtSource.Rows[0][repLookupEdit.ValueMember].ToString()))
                                        {

                                            DataRow row = dtSource.NewRow();
                                            row[repLookupEdit.DisplayMember] = String.Empty;
                                            row[repLookupEdit.ValueMember] = String.Empty;
                                            row["Key"] = "DummyField";
                                            dtSource.Rows.InsertAt(row, 0);
                                        }
                                    }
                                    repLookupEdit.DataSource = dtSource;
                                    DevExpress.XtraEditors.Controls.LookUpColumnInfo repColumn = new DevExpress.XtraEditors.Controls.LookUpColumnInfo();
                                    repColumn.FieldName = "Text";
                                    repColumn.Caption = " ";
                                    repColumn.Width = 100;
                                    repLookupEdit.Columns.Add(repColumn);
                                    repLookupEdit.PopupWidth = repColumn.Width;
                                    column.ColumnEdit = repLookupEdit;
                                }
                                else
                                {
                                    
                                    column.ColumnEdit = InitColumnRepositoryFromFieldFormatGroup(strTableName, objAAColumnAliasInfo.AAColumnAliasName);
                                }
                            }

                            
                            if (column.ColumnEdit != null)
                                InitColumnRepositoryFormat(column, strTableName, objAAColumnAliasInfo.AAColumnAliasName);
                            else
                                InitColumnFormat(column, strTableName, objAAColumnAliasInfo.AAColumnAliasName);

                            column.OptionsColumn.AllowEdit = false;
                            gridView.Columns.Add(column);
                        }
                        else
                        {
                            gridView.Columns[objAAColumnAliasInfo.AAColumnAliasName].Caption = objAAColumnAliasInfo.AAColumnAliasCaption;
                        }
                    }
                }
            }
        }

        
        public DevExpress.XtraEditors.Repository.RepositoryItem InitColumnRepositoryFromFieldFormatGroup(String strTableName, String strColumnName)
        {
            STFieldFormatGroupsController objFieldFormatGroupsController = new STFieldFormatGroupsController();
            STFieldFormatGroupsInfo objFieldFormatGroupsInfo = objFieldFormatGroupsController.GetFieldFormatGroupByModuleNameAndTableNameAndColumnName(this.Screen.Module.Name, strTableName, strColumnName);
            if (objFieldFormatGroupsInfo != null)
            {
                if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupRepository))
                {
                    return THSUtil.GetRepositoryItemFromText(objFieldFormatGroupsInfo.STFieldFormatGroupRepository);
                }
            }
            return null;
        }

        
        public void InitColumnRepositoryFormat(DevExpress.XtraGrid.Columns.GridColumn column, String strTableName, String strColumnName)
        {
            STFieldFormatGroupsController objFieldFormatGroupsController = new STFieldFormatGroupsController();
            STFieldFormatGroupsInfo objFieldFormatGroupsInfo = objFieldFormatGroupsController.GetFieldFormatGroupByModuleNameAndTableNameAndColumnName(this.Screen.Module.Name, strTableName, strColumnName);
            if (objFieldFormatGroupsInfo != null)
            {
                DevExpress.XtraEditors.Repository.RepositoryItem rep = column.ColumnEdit;
                if (objFieldFormatGroupsInfo.STFieldFormatGroupBackColor > 0)
                {
                    rep.Appearance.BackColor = Color.FromArgb(objFieldFormatGroupsInfo.STFieldFormatGroupBackColor);
                    rep.Appearance.Options.UseBackColor = true;
                }
                if (objFieldFormatGroupsInfo.STFieldFormatGroupForeColor > 0)
                {
                    rep.Appearance.ForeColor = Color.FromArgb(objFieldFormatGroupsInfo.STFieldFormatGroupForeColor);
                    rep.Appearance.Options.UseForeColor = true;
                }

                String strDefaultFontName = "Tahoma";
                float fDefaultFontSize = 8.25F;
                if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupFontName))
                    strDefaultFontName = objFieldFormatGroupsInfo.STFieldFormatGroupFontName;
                if (objFieldFormatGroupsInfo.STFieldFormatGroupFontSize > 0)
                    fDefaultFontSize = objFieldFormatGroupsInfo.STFieldFormatGroupFontSize;
                rep.Appearance.Font = new Font(strDefaultFontName, fDefaultFontSize);
                rep.Appearance.Options.UseFont = true;

                if (rep.GetType() == typeof(DevExpress.XtraEditors.Repository.RepositoryItemTextEdit))
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemTextEdit repText = (DevExpress.XtraEditors.Repository.RepositoryItemTextEdit)rep;
                    //hieu nguyen change,fix round group =0,Nov 19,2009
                    //if (objFieldFormatGroupsInfo.STFieldFormatGroupDecimalRound > 0)
                    //{
                    //    repText.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                    //    repText.Mask.EditMask = String.Format("n{0}", objFieldFormatGroupsInfo.STFieldFormatGroupDecimalRound);
                    //    repText.Mask.UseMaskAsDisplayFormat = true;
                    //}
                    //else
                    //{
                    //    if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupMaskType))
                    //    {
                    //        repText.Mask.MaskType = THSUtil.GetMaskTypeFromText(objFieldFormatGroupsInfo.STFieldFormatGroupMaskType);
                    //        repText.Mask.EditMask = objFieldFormatGroupsInfo.STFieldFormatGroupMaskEdit;
                    //        repText.Mask.UseMaskAsDisplayFormat = true;
                    //    }
                    //    if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType))
                    //    {
                    //        repText.DisplayFormat.FormatType = THSUtil.GetFormatTypeFromText(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType);
                    //        repText.DisplayFormat.FormatString = objFieldFormatGroupsInfo.STFieldFormatGroupFormatString;
                    //    }
                    //}
                    if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupMaskType))
                    {
                        repText.Mask.MaskType = THSUtil.GetMaskTypeFromText(objFieldFormatGroupsInfo.STFieldFormatGroupMaskType);
                        repText.Mask.EditMask = objFieldFormatGroupsInfo.STFieldFormatGroupMaskEdit;
                        repText.Mask.UseMaskAsDisplayFormat = true;
                    }
                    if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType))
                    {
                        repText.DisplayFormat.FormatType = THSUtil.GetFormatTypeFromText(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType);
                        repText.DisplayFormat.FormatString = objFieldFormatGroupsInfo.STFieldFormatGroupFormatString;
                    }
                    else
                    {
                        repText.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                        repText.Mask.EditMask = String.Format("n{0}", objFieldFormatGroupsInfo.STFieldFormatGroupDecimalRound);
                        repText.Mask.UseMaskAsDisplayFormat = true;
                    }
                }
            }
        }

        
        public void InitColumnFormat(DevExpress.XtraGrid.Columns.GridColumn column, String strTableName, String strColumnName)
        {
            STFieldFormatGroupsController objFieldFormatGroupsController = new STFieldFormatGroupsController();
            STFieldFormatGroupsInfo objFieldFormatGroupsInfo = objFieldFormatGroupsController.GetFieldFormatGroupByModuleNameAndTableNameAndColumnName(this.Screen.Module.Name, strTableName, strColumnName);
            if (objFieldFormatGroupsInfo != null)
            {
                if (objFieldFormatGroupsInfo.STFieldFormatGroupBackColor > 0)
                {
                    column.AppearanceCell.BackColor = Color.FromArgb(objFieldFormatGroupsInfo.STFieldFormatGroupBackColor);
                    column.AppearanceCell.Options.UseBackColor = true;
                }
                if (objFieldFormatGroupsInfo.STFieldFormatGroupForeColor > 0)
                {
                    column.AppearanceCell.ForeColor = Color.FromArgb(objFieldFormatGroupsInfo.STFieldFormatGroupForeColor);
                    column.AppearanceCell.Options.UseForeColor = true;
                }

                String strDefaultFontName = "Tahoma";
                float fDefaultFontSize = 8.25F;
                if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupFontName))
                    strDefaultFontName = objFieldFormatGroupsInfo.STFieldFormatGroupFontName;
                if (objFieldFormatGroupsInfo.STFieldFormatGroupFontSize > 0)
                    fDefaultFontSize = objFieldFormatGroupsInfo.STFieldFormatGroupFontSize;
                column.AppearanceCell.Font = new Font(strDefaultFontName, fDefaultFontSize);
                column.AppearanceCell.Options.UseFont = true;
                //hieu nguyen change,fix round group =0,Nov 19,2009
                //if (objFieldFormatGroupsInfo.STFieldFormatGroupDecimalRound > 0)
                //{
                //    column.ColumnEdit = THSUtil.GetRepositoryItemFromText("RepositoryItemTextEdit");
                //    InitColumnRepositoryFormat(column, strTableName, strColumnName);
                //}
                //else
                //{
                //    if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType))
                //    {
                //        column.DisplayFormat.FormatType = THSUtil.GetFormatTypeFromText(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType);
                //        column.DisplayFormat.FormatString = objFieldFormatGroupsInfo.STFieldFormatGroupFormatString;
                //    }
                //}
                if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType))
                {
                    column.DisplayFormat.FormatType = THSUtil.GetFormatTypeFromText(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType);
                    column.DisplayFormat.FormatString = objFieldFormatGroupsInfo.STFieldFormatGroupFormatString;
                }

                else
                {
                    if (!String.IsNullOrEmpty( objFieldFormatGroupsInfo.STFieldFormatGroupRepository ))
                        column.ColumnEdit=THSUtil.GetRepositoryItemFromText( objFieldFormatGroupsInfo.STFieldFormatGroupRepository );
                    else
                            column.ColumnEdit = THSUtil.GetRepositoryItemFromText("RepositoryItemTextEdit");
                    InitColumnRepositoryFormat(column, strTableName, strColumnName);
                }
            }
            //hieu nguyen add ,fix Default DateTime format if does not exists config reponsitory ,field format
            else
            {
                String strDataType = THSDbUtil.GetColumnDataType(strTableName, strColumnName);
                if (!String.IsNullOrEmpty(strDataType))
                {
                    if (strDataType.Contains("datetime"))
                    {
                        column.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                        column.DisplayFormat.FormatString = "d";
                    }
                }
            }
        }
        #endregion

        #region Module Items GridControl View functions
        protected virtual void InvalidateItemTypeControls()
        {
            bool isProductType = false;
            STFieldsController objSTFieldsController = new STFieldsController();
            STFieldsInfo objItemProductTypeFieldInfo = objSTFieldsController.GetFirstFieldByModuleIDAndUserGroupIDAndFieldDataSourceAndFieldDataMemberAndFieldGroup(
                                                                                ((BaseModuleERP)Screen.Module).ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                                                String.Empty, "Product", "ItemType");

            ERPModuleEntities entity = ((BaseModuleERP)Screen.Module).CurrentModuleEntity;

           
            String strMainObjectName = THSUtil.GetTableNameFromBusinessObject(entity.MainObject);
            String strModuleItemsObjectName = strMainObjectName.Substring(0, 2) + Screen.Module.Name + "Items";
            String strModuleItemTypePropertyName = strModuleItemsObjectName.Substring(0, strModuleItemsObjectName.Length - 1) + "TypeCombo";


            //String strItemType = ((FASellOrderItemsInfo)entity.ModuleObjects[SellOrderEntities.strFASellOrderItemsObjectName]).FASellOrderItemTypeCombo;
            String strItemType = THSDbUtil.GetPropertyValue(entity.ModuleObjects[strModuleItemsObjectName], strModuleItemTypePropertyName).ToString();

            if (strItemType == ADConfigValueUtility.cstItemTypeProduct)
            {
                isProductType = true;
            }
            if (objItemProductTypeFieldInfo != null)
                ((DevExpress.XtraEditors.CheckEdit)Screen.Module.Controls[objItemProductTypeFieldInfo.STFieldName]).Checked = isProductType;
        }
        #endregion

        public object Clone()
        {
            return this.MemberwiseClone();
        }

        
        private void NavigatorButton_Click(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            if (e.Button.Hint == "Customize")
                CustomizeColumnGridControl();
            else
                if (e.Button.Hint == "Save Customization")
                    SaveCustomizeColumnGridControl();
                else if (e.Button.Hint == "Export")
                {
                    SaveFileDialog dlgSave = new SaveFileDialog();
                    dlgSave.Filter = "Microsoft Excel|*.xls";
                    DialogResult dlgResult = dlgSave.ShowDialog();
                    if (dlgResult == DialogResult.OK)
                    {
                        ExportTo(new ExportXlsProvider(dlgSave.FileName));
                        if (DialogResult.Yes == MessageBox.Show("Xuất file Excel thành công! Bạn có muốn mở file ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                        {
                            System.Diagnostics.Process.Start(dlgSave.FileName);
                        }
                    }

                }
                else if (e.Button.Hint == "Print")
                {
                    PrintPriview();
                    //Print();
                }
                else if (e.Button.Hint == "Refresh")
                {
                    this.DataSource = null;
                    this.RefreshDataSource();
                    InitGridControlDataSource();
                }

        }

        /// <summary>
        /// Customize Column grid Control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="strEventName"></param>
        /// <THSparam name="GridControlName" type="String"></THSparam>
        /// 
        private void CustomizeColumnGridControl()
        {
            ((DevExpress.XtraGrid.Views.Grid.GridView)this.MainView).ColumnsCustomization();
        }

        /// <summary>
        /// Save customize columns of THSGridControl
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="strEventName"></param>
        /// <THSparam name="GridControlName" type="String"></THSparam>
        private void SaveCustomizeColumnGridControl()
        {
            STFieldsInfo objSTFieldsInfo = new STFieldsController().GetFieldBySTModuleIDAndSTUserGroupIDAndSTFieldName(
                                                                        ((BaseModuleERP)Screen.Module).ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                                        this.Name);
                if (objSTFieldsInfo != null)
                {
                    STFieldColumnsController objSTFieldColumnsController = new STFieldColumnsController();
                    objSTFieldColumnsController.DeleteByForeignColumn("STFieldID", objSTFieldsInfo.STFieldID);

                    foreach (DevExpress.XtraGrid.Columns.GridColumn GridColumn in ((DevExpress.XtraGrid.Views.Grid.GridView)(this.ViewCollection[0])).Columns)
                    {
                        if (GridColumn.Visible)
                        {
                            STFieldColumnsInfo objSTFieldColumnsInfo = new STFieldColumnsInfo();
                            objSTFieldColumnsInfo.STFieldID = objSTFieldsInfo.STFieldID;
                            objSTFieldColumnsInfo.STFieldColumnFieldName = GridColumn.FieldName;
                            objSTFieldColumnsInfo.STFieldColumnName = GridColumn.Name;
                            objSTFieldColumnsInfo.STFieldColumnCaption = GridColumn.Caption;
                            objSTFieldColumnsInfo.STFieldColumnWidth = GridColumn.Width;
                            objSTFieldColumnsInfo.STFieldColumnVisibleIndex = GridColumn.VisibleIndex;

                            objSTFieldColumnsController.CreateObject(objSTFieldColumnsInfo);
                        }
                    }
                    MessageBox.Show("Save successfully.", "#Message#", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
        }
        /// <summary>
        /// Export data to excel
        /// </summary>
        /// <param name="provider"></param>
        /// 
        private void ExportTo(IExportProvider provider)
        {
            Cursor currentCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            this.FindForm().Refresh();
            DevExpress.XtraGrid.Export.BaseExportLink link = this.Views[0].CreateExportLink(provider);
            (link as DevExpress.XtraGrid.Export.GridViewExportLink).ExpandAll = false;
            link.ExportTo(true);
            provider.Dispose();


            Cursor.Current = currentCursor;
        }
        public void PrintPriview()
        {
            PrintingSystem printingSystem = new PrintingSystem();
            PrintableComponentLink printLink = new PrintableComponentLink();
            try
            {
                //Set to landscape
                printingSystem.PageSettings.Landscape = true;
                this.Cursor = Cursors.WaitCursor;
                printLink.Component = this;
                printLink.CreateDocument(printingSystem);
                printingSystem.PreviewFormEx.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                this.Cursor = Cursors.Default;
                printingSystem.Dispose();
                printLink.Dispose();
            }

        }
        /// <summary>
        /// Invalidate lookup edit columns to reflect all changes of lookup table
        /// </summary>
        /// 
        public virtual void InvalidateLookupEditColumns()
        {
            DevExpress.XtraGrid.Views.Grid.GridView gridView = (DevExpress.XtraGrid.Views.Grid.GridView)this.MainView;
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
                if (column.ColumnEdit != null && column.ColumnEdit.GetType() == typeof(DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit))
                {
                   
                    DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit rep = (DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit)column.ColumnEdit;
                    String strLookupTable = THSDbUtil.GetPrimaryTableWhichForeignColumnReferenceTo(THSDataSource, column.FieldName);
                    //Update lookup table if there is any changes to it
                    DateTime dtLastCreatedDate = THSDbUtil.GetLastCreatedDateOfTable(strLookupTable);
                    DateTime dtLastUpdatedDate = THSDbUtil.GetLastUpdatedDateOfTable(strLookupTable);
                    if (dtLastCreatedDate.CompareTo(((DateTime)THSApp.LookupTablesUpdatedDate[strLookupTable])) > 0 ||
                        dtLastUpdatedDate.CompareTo(((DateTime)THSApp.LookupTablesUpdatedDate[strLookupTable])) > 0)
                    {
                        //Refesh Data Source
                        BaseBusinessController objLookupTableController = BusinessControllerFactory.GetBusinessController(strLookupTable + "Controller");
                        if (objLookupTableController != null)
                        {
                            DataSet ds = objLookupTableController.GetAllObjects();
                            if (ds.Tables.Count > 0)
                            {
                                // Update Last Updated Date of Lookup Table

                                THSApp.LookupTablesUpdatedDate[strLookupTable] = DateTime.Now;
                                ((DataSet)THSApp.LookupTables[strLookupTable]).Tables.Clear();
                                ((DataSet)THSApp.LookupTables[strLookupTable]).Tables.Add(ds.Tables[0].Copy());
                            }
                        }
                    }
                    rep.DataSource =((DataSet)THSApp.LookupTables[strLookupTable]).Tables[0];
                    
                    
                }
        }
    }
}
